﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml.Linq;
using System.ServiceModel;
using System.Threading;

namespace DuplexDeviceEvent
{
    class DeviceEventRunner
    {
        private static IDeviceEventServiceClient theClient = null;
        private static Timer eventTimer = null;
        private static string clientId = String.Empty;

        static DeviceEventRunner()
        {
            eventTimer = new Timer(updateClient, null, 1000, 5000);
        }

        private static void updateClient(Object stateinfo)
        {
            try
            {
                if (theClient != null)
                {
                    Console.WriteLine("Updating Client {0}", clientId);
                    DeviceEventData eventData = new DeviceEventData();
                    eventData.message = "Test Data";
                    eventData.timestamp = DateTime.Now;
                    theClient.SendDeviceEventData(eventData);
                }
            }
            catch (CommunicationException ex)
            {
                //client error so dispose of client
                Console.WriteLine("Client Error: {0}", ex.Message);
                Console.WriteLine("Closing connection to client {0}", clientId);
                theClient = null;
                clientId = String.Empty;
            }
        }

        public static void Register(IDeviceEventServiceClient client, string id)
        {
            theClient = client;
            clientId = id;
            Console.WriteLine("Client {0} registered.", id);
        }

        public static void Dispose()
        {
            eventTimer.Dispose();
        }
    }
}